package com.flycms.modules.site.controller;

import com.flycms.common.controller.BaseController;
import com.flycms.common.exception.ApiAssert;
import com.flycms.common.utils.result.LayResult;
import com.flycms.common.utils.result.Result;
import com.flycms.common.validator.Sort;
import com.flycms.modules.site.entity.Site;
import com.flycms.modules.site.entity.SiteColumnTree;
import com.flycms.modules.site.entity.SiteColumn;
import com.flycms.modules.site.entity.SiteColumnBO;
import com.flycms.modules.system.service.SystemModuleService;
import com.flycms.modules.template.entity.SiteTemplatePage;
import com.flycms.modules.template.service.SiteTemplateService;
import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * 公共的
 * @author 孙开飞
 */
@Controller
@RequestMapping("/member/column")
public class ColumnMemberController extends BaseController {
    @Autowired
    private SystemModuleService systemModuleService;

    @Autowired
    private SiteTemplateService siteTemplateService;

    @GetMapping("/add{url.suffix}")
    public Object add(@RequestParam(value = "siteid", required = false) String siteid,
                      @RequestParam(value = "parentId", defaultValue = "0") String parentId, Model model){
        ApiAssert.notTrue(siteid == null || !NumberUtils.isNumber(siteid), "网站id为空或者类型错误");
        ApiAssert.notTrue(!siteCompanyService.checkSiteCompany(Long.parseLong(siteid)), "您不是网站管理员，请勿非法操作");

        //父级分类
        if(!StringUtils.isEmpty(siteid) && (!StringUtils.isEmpty(parentId) && Long.parseLong(parentId) > 0l)){
            String parentName=siteColumnService.parentName(Long.parseLong(parentId),Long.parseLong(siteid));
            model.addAttribute("parentName",parentName);
        }
        model.addAttribute("parentId",parentId);
        //模型列表
        model.addAttribute("modulelist",systemModuleService.selectModuleList());
        //网站id
        model.addAttribute("siteId",siteid);
        return "system/member/site/column/add";
    }


    @PostMapping("/add{url.suffix}")
    @ResponseBody
    public Object add(@Valid SiteColumnBO siteColumnBO, BindingResult bindingResult) throws java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException
    {
        //javabean 映射工具
        //MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        //MapperFacade mapper = mapperFactory.getMapperFacade();

        List<ObjectError> error=null;
        //返回boolean 是为了验证@Validated后面bean 里是否有不符合注解条件的错误信息
        if(bindingResult.hasErrors()){
            //获得所有错误信息返回list集合
            error=bindingResult.getAllErrors();
            for (ObjectError o:error) {
                //获得不符合要求的message
                return Result.failure(o.getDefaultMessage());
            }

        }
        ApiAssert.notTrue(!siteCompanyService.checkSiteCompany(Long.parseLong(siteColumnBO.getSiteId())), "您不是网站管理员，请勿非法操作");
        if(!StringUtils.isEmpty(siteColumnBO.getTempindex())){
            ApiAssert.notTrue(!NumberUtils.isDigits(siteColumnBO.getTempindex()), "封面模板id参数错误");
        }
        if(!StringUtils.isEmpty(siteColumnBO.getTemplist())){
            ApiAssert.notTrue(!NumberUtils.isDigits(siteColumnBO.getTemplist()), "列表模板id参数错误");
        }
        if(!StringUtils.isEmpty(siteColumnBO.getTempcontent())){
            ApiAssert.notTrue(!NumberUtils.isDigits(siteColumnBO.getTempcontent()), "内容页面模板id参数错误");
        }
        if(!StringUtils.isEmpty(siteColumnBO.getTempalone())){
            ApiAssert.notTrue(!NumberUtils.isDigits(siteColumnBO.getTempalone()), "单独页面模板id参数错误");
        }

        Mapper mapper = DozerBeanMapperBuilder.buildDefault();
        SiteColumn column = mapper.map(siteColumnBO, SiteColumn.class);
        return siteColumnService.addUserSiteColumn(column);
    }

    @GetMapping("/edit{url.suffix}")
    public Object edit(@RequestParam(value = "siteid", required = false) String siteid,
                      @RequestParam(value = "id", required = false) String id, Model model){
        ApiAssert.notTrue(siteid == null || !NumberUtils.isNumber(siteid), "网站id为空或者类型错误");
        ApiAssert.notTrue(id == null || !NumberUtils.isNumber(id), "分类id为空或者类型错误");
        ApiAssert.notTrue(!siteCompanyService.checkSiteCompany(Long.parseLong(siteid)), "您不是网站管理员，请勿非法操作");

        Site site=siteService.findById(Long.parseLong(siteid));

        SiteColumn column=siteColumnService.findByIdAndSiteId(Long.parseLong(id),Long.parseLong(siteid));

        String parentName=siteColumnService.parentName(column.getParentId(),Long.parseLong(siteid));

        List<SiteTemplatePage> tempindexList=siteTemplateService.selectTemplatePageList(column.getSiteId(),site.getTemplateId(),column.getChannel(),1);

        List<SiteTemplatePage> templist=siteTemplateService.selectTemplatePageList(column.getSiteId(),site.getTemplateId(),column.getChannel(),2);

        List<SiteTemplatePage> tempcontent=siteTemplateService.selectTemplatePageList(column.getSiteId(),site.getTemplateId(),column.getChannel(),3);

        List<SiteTemplatePage> tempalone=siteTemplateService.selectTemplatePageList(column.getSiteId(),site.getTemplateId(),column.getChannel(),4);
        //当前父级分类信息
        model.addAttribute("parentName",parentName);
        //当前分类所有信息
        model.addAttribute("column",column);
        //父级分类
        model.addAttribute("columnlist",siteColumnService.selectColumnListByParentId(Long.parseLong(siteid),0L));
        //模型列表
        model.addAttribute("modulelist",systemModuleService.selectModuleList());
        //封面模板列表
        model.addAttribute("tempindexList",tempindexList);
        //列表模板列表
        model.addAttribute("templist",templist);
        //内容页面模板列表
        model.addAttribute("tempcontent",tempcontent);
        //单独页面模板列表
        model.addAttribute("tempalone",tempalone);
        //网站id
        model.addAttribute("siteId",siteid);
        model.addAttribute("id",id);
        return "system/member/site/column/edit";
    }


    @PostMapping("/edit{url.suffix}")
    @ResponseBody
    public Object edit(@Valid SiteColumnBO siteColumnBO, BindingResult bindingResult)
    {
        //javabean 映射工具
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        MapperFacade mapper = mapperFactory.getMapperFacade();

        List<ObjectError> error=null;
        //返回boolean 是为了验证@Validated后面bean 里是否有不符合注解条件的错误信息
        if(bindingResult.hasErrors()){
            //获得所有错误信息返回list集合
            error=bindingResult.getAllErrors();
            for (ObjectError o:error) {
                //获得不符合要求的message
                return Result.failure(o.getDefaultMessage());
            }

        }
        if (!siteColumnService.checkColumnNode(Long.parseLong(siteColumnBO.getSiteId()),Long.parseLong(siteColumnBO.getId()),Long.parseLong(siteColumnBO.getParentId()))){
            return Result.failure("不能把自己当为父级或者自己的子分类下");
        }
        if(!StringUtils.isEmpty(siteColumnBO.getId())){
            ApiAssert.notTrue(!NumberUtils.isDigits(siteColumnBO.getTemplist()), "列表模板id参数错误");
        }
        ApiAssert.notTrue(!siteCompanyService.checkSiteCompany(Long.parseLong(siteColumnBO.getSiteId())), "您不是网站管理员，请勿非法操作");
        if(!StringUtils.isEmpty(siteColumnBO.getTempindex())){
            ApiAssert.notTrue(!NumberUtils.isDigits(siteColumnBO.getTempindex()), "封面模板id参数错误");
        }
        if(!StringUtils.isEmpty(siteColumnBO.getTemplist())){
            ApiAssert.notTrue(!NumberUtils.isDigits(siteColumnBO.getTemplist()), "列表模板id参数错误");
        }
        if(!StringUtils.isEmpty(siteColumnBO.getTempcontent())){
            ApiAssert.notTrue(!NumberUtils.isDigits(siteColumnBO.getTempcontent()), "内容页面模板id参数错误");
        }
        if(!StringUtils.isEmpty(siteColumnBO.getTempalone())){
            ApiAssert.notTrue(!NumberUtils.isDigits(siteColumnBO.getTempalone()), "单独页面模板id参数错误");
        }
        SiteColumn column = mapper.map(siteColumnBO,SiteColumn.class);
        return siteColumnService.editUserSiteColumn(column);
    }

    //分类时弹窗选择父级分类树
    @GetMapping("/columnzTree{url.suffix}")
    @ResponseBody
    public Object columnzTree(@RequestParam(value = "siteid", required = false) String siteid){
        ApiAssert.notTrue(siteid == null || !NumberUtils.isNumber(siteid), "网站id为空或者类型错误");
        ApiAssert.notTrue(!siteCompanyService.checkSiteCompany(Long.parseLong(siteid)), "您不是网站管理员，请勿非法操作");
        //return siteColumnService.findColumnTreeBySiteId(Long.parseLong(siteid));
        List<SiteColumnTree> treelist = new ArrayList<SiteColumnTree>();
        SiteColumnTree tree=new SiteColumnTree();
        tree.setId(0l);
        tree.setName("顶级分类");
        tree.setChildren(siteColumnService.findColumnTreeBySiteId(Long.parseLong(siteid)));
        treelist.add(tree);
        return treelist;
    }

    //用户发布内容是选择内容分类下拉菜单
    @GetMapping("/columnselect{url.suffix}")
    @ResponseBody
    public Object columnSelect(@RequestParam(value = "siteid", required = false) String siteid,
                               @RequestParam(value = "channel", required = false) String channel){
        ApiAssert.notTrue(siteid == null || !NumberUtils.isNumber(siteid), "网站id为空或者类型错误");
        ApiAssert.notTrue(channel == null || !NumberUtils.isNumber(channel), "模型id为空或者类型错误");
        ApiAssert.notTrue(!siteCompanyService.checkSiteCompany(Long.parseLong(siteid)), "您不是网站管理员，请勿非法操作");
        return siteColumnService.findColumnTreeBySiteId(Long.parseLong(siteid),Long.parseLong(channel));
    }

    @GetMapping("/columnTree{url.suffix}")
    @ResponseBody
    public Object columnTree(@RequestParam(value = "siteid", required = false) String siteid){
        ApiAssert.notTrue(siteid == null || !NumberUtils.isNumber(siteid), "网站id为空或者类型错误");
        ApiAssert.notTrue(!siteCompanyService.checkSiteCompany(Long.parseLong(siteid)), "您不是网站管理员，请勿非法操作");
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> status = new HashMap<>();
        status.put("code",200);
        status.put("message","操作成功");
        map.put("status",status);
        map.put("data",siteColumnService.findColumnTreeBySiteId(Long.parseLong(siteid)));
        return map;
    }

    @GetMapping("/columnform{url.suffix}")
    public Object columnForm(@RequestParam(value = "siteid", required = false) String siteid,Model model){
        ApiAssert.notTrue(siteid == null || !NumberUtils.isNumber(siteid), "网站id为空或者类型错误");
        ApiAssert.notTrue(!siteCompanyService.checkSiteCompany(Long.parseLong(siteid)), "您不是网站管理员，请勿非法操作");
        //网站id
        model.addAttribute("siteid",siteid);
        return "system/member/site/column/columnform";
    }

    /**
     * 网站分类列表
     *
     * @return
     */
    @GetMapping("/list{url.suffix}")
    public String siteList(@RequestParam(value = "siteid", defaultValue = "0") String siteid,
                           @RequestParam(value = "id", defaultValue = "0") String id, Model model)
    {
        ApiAssert.notTrue(siteid == null || !NumberUtils.isNumber(siteid), "网站id为空或者类型错误");
        ApiAssert.notTrue(!siteCompanyService.checkSiteCompany(Long.parseLong(siteid)), "您不是网站管理员，请勿非法操作");
        model.addAttribute("siteId",siteid);
        return "system/member/site/column/list";
    }

    @GetMapping("/listData{url.suffix}")
    @ResponseBody
    public Object siteList(@RequestParam(value = "siteid", defaultValue = "0") String siteid,
                           @RequestParam(value = "page",defaultValue = "1") Integer page,
                           @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                           @Sort(accepts = {"add_time", "id"}) @RequestParam(defaultValue = "add_time") String sort,
                           @RequestParam(defaultValue = "desc") String order) {
        ApiAssert.notTrue(siteid == null || !NumberUtils.isNumber(siteid), "网站id为空或者类型错误");
        ApiAssert.notTrue(!siteCompanyService.checkSiteCompany(Long.parseLong(siteid)), "您不是网站管理员，请勿非法操作");
        return LayResult.success(0,"true", 0, siteColumnService.selectColumnListTreetable(Long.parseLong(siteid)));
    }
}
